import request from '@/utils/request'

/**
 * 景区管理 API
 */
export const scenicApi = {
  /**
   * 获取景区分页列表
   * @param {Object} params - 查询参数
   * @param {number} params.pageNum - 页码
   * @param {number} params.pageSize - 每页数量
   * @param {string} params.name - 景点名称搜索
   * @param {number} params.status - 状态筛选(0:下架,1:上架)
   * @returns {Promise} 景区列表
   */
  getPage: async (params) => {
    try {
      console.log('发送景区分页查询请求，参数:', params)
      
      // 构建查询参数，只传递有值的参数
      const queryParams = {
        pageNum: params.pageNum || 1,
        pageSize: params.pageSize || 10
      }
      
      // 搜索条件
      if (params.name && params.name.trim()) {
        queryParams.name = params.name.trim()
      }
      
      // 状态筛选
      if (params.status !== undefined && params.status !== null) {
        queryParams.status = params.status
      }
      
      console.log('最终发送的查询参数:', queryParams)
      
      const response = await fetch('/api/admin/scenicSpot/page', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(queryParams)
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      console.log('接收到的景区数据:', result)
      
      if (result.code === 200) {
        return result.data
      } else {
        throw new Error(result.msg || '获取景区列表失败')
      }
    } catch (error) {
      console.error('获取景区列表失败:', error)
      throw error
    }
  },

  /**
   * 根据ID获取景区详情
   * @param {number} id - 景区ID
   * @returns {Promise} 景区详情
   */
  getById: async (id) => {
    try {
      const response = await request.get(`/scenic/${id}`)
      return response.data
    } catch (error) {
      throw error
    }
  },

  /**
   * 根据景点预约ID获取景点预约详细信息
   * @param {number} id - 景点预约ID
   * @returns {Promise} 景点预约详情
   */
  getScenicOrderDetails: async (id) => {
    try {
      console.log('获取景点预约详情，ID:', id)
      
      const response = await fetch(`/api/admin/scenicOrder/details/${id}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        }
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      console.log('接收到的景点预约详情:', result)
      
      if (result.code === 200) {
        return result.data
      } else {
        throw new Error(result.msg || '获取景点预约详情失败')
      }
    } catch (error) {
      console.error('获取景点预约详情失败:', error)
      throw error
    }
  },

  /**
   * 创建景区
   * @param {Object} data - 景区数据
   * @returns {Promise} 创建结果
   */
  create: async (data) => {
    try {
      const response = await request.post('/scenic', data)
      return response.data
    } catch (error) {
      throw error
    }
  },

  /**
   * 添加景点信息（调用真实接口）
   * @param {Object} scenicSpotData - 景点数据
   * @param {File} coverImageFile - 封面图片文件
   * @returns {Promise} 添加结果
   */
  insert: async (scenicSpotData, coverImageFile) => {
    try {
      console.log('发送添加景点请求，数据:', scenicSpotData)
      
      // 创建 FormData 对象
      const formData = new FormData()
      
      // 添加景点基本信息
      Object.keys(scenicSpotData).forEach(key => {
        if (scenicSpotData[key] !== null && scenicSpotData[key] !== undefined) {
          formData.append(key, scenicSpotData[key])
        }
      })
      
      // 添加封面图片文件
      if (coverImageFile) {
        formData.append('coverImageFile', coverImageFile)
      }
      
      console.log('FormData 内容:')
      for (let [key, value] of formData.entries()) {
        console.log(key, value)
      }
      
      const response = await fetch('/api/admin/scenicSpot/insert', {
        method: 'POST',
        body: formData
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      console.log('接收到的添加景点响应:', result)
      
      if (result.code === 200) {
        return result
      } else {
        throw new Error(result.msg || '添加景点失败')
      }
    } catch (error) {
      console.error('添加景点失败:', error)
      throw error
    }
  },

  /**
   * 更新景点信息（调用真实接口）
   * @param {Object} scenicSpotData - 景点数据（包含id）
   * @param {File} coverImageFile - 封面图片文件（可选）
   * @returns {Promise} 更新结果
   */
  updateById: async (scenicSpotData, coverImageFile) => {
    try {
      console.log('发送更新景点请求，数据:', scenicSpotData)
      
      // 创建 FormData 对象
      const formData = new FormData()
      
      // 添加景点基本信息
      Object.keys(scenicSpotData).forEach(key => {
        if (scenicSpotData[key] !== null && scenicSpotData[key] !== undefined) {
          formData.append(key, scenicSpotData[key])
        }
      })
      
      // 添加封面图片文件（如果有新上传的图片）
      if (coverImageFile) {
        formData.append('coverImageFile', coverImageFile)
      }
      
      console.log('FormData 内容:')
      for (let [key, value] of formData.entries()) {
        console.log(key, value)
      }
      
      const response = await fetch('/api/admin/scenicSpot/update', {
        method: 'POST',
        body: formData
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      console.log('接收到的更新景点响应:', result)
      
      if (result.code === 200) {
        return result
      } else {
        throw new Error(result.msg || '更新景点失败')
      }
    } catch (error) {
      console.error('更新景点失败:', error)
      throw error
    }
  },

  /**
   * 更新景区信息
   * @param {number} id - 景区ID
   * @param {Object} data - 更新数据
   * @returns {Promise} 更新结果
   */
  update: async (id, data) => {
    try {
      const response = await request.put(`/scenic/${id}`, data)
      return response.data
    } catch (error) {
      throw error
    }
  },

  /**
   * 删除景区
   * @param {number} id - 景区ID
   * @returns {Promise} 删除结果
   */
  delete: async (id) => {
    try {
      const response = await request.delete(`/scenic/${id}`)
      return response.data
    } catch (error) {
      throw error
    }
  },

  /**
   * 根据景点ID删除景点（调用真实接口）
   * @param {number} id - 景点ID
   * @returns {Promise} 删除结果
   */
  deleteById: async (id) => {
    try {
      console.log('发送删除景点请求，ID:', id)
      
      const response = await fetch(`/api/admin/scenicSpot/delete/${id}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        }
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      console.log('接收到的删除景点响应:', result)
      
      if (result.code === 200) {
        return result
      } else {
        throw new Error(result.msg || '删除景点失败')
      }
    } catch (error) {
      console.error('删除景点失败:', error)
      throw error
    }
  },

  /**
   * 批量删除景区
   * @param {Array} ids - 景区ID数组
   * @returns {Promise} 删除结果
   */
  batchDelete: async (ids) => {
    try {
      const response = await request.delete('/scenic/batch', { data: { ids } })
      return response.data
    } catch (error) {
      throw error
    }
  },

  /**
   * 更新景区状态
   * @param {number} id - 景区ID
   * @param {string} status - 新状态
   * @returns {Promise} 更新结果
   */
  updateStatus: async (id, status) => {
    try {
      const response = await request.put(`/scenic/${id}/status`, { status })
      return response.data
    } catch (error) {
      throw error
    }
  },

  /**
   * 获取景区统计信息
   * @returns {Promise} 统计数据
   */
  getStats: async () => {
    try {
      const response = await request.get('/scenic/stats')
      return response.data
    } catch (error) {
      throw error
    }
  }
}

// 兼容旧的导出方式
export const getScenicPage = scenicApi.getPage
export const getScenicById = scenicApi.getById
export const createScenic = scenicApi.create
export const insertScenic = scenicApi.insert
export const updateScenic = scenicApi.update
export const updateScenicById = scenicApi.updateById
export const deleteScenic = scenicApi.delete
export const deleteScenicById = scenicApi.deleteById
export const updateScenicStatus = scenicApi.updateStatus
export const getScenicOrderDetails = scenicApi.getScenicOrderDetails